<?php

	//header( 'Content-Type: application/javascript' );
	
	function packJs( $p_srcDir, $ignoreList = array() )
	{
		$data = "";
		$jsFiles = scanRecursively( $p_srcDir ); 
		$bigJs = "";
		
		foreach( $jsFiles as $jsFile )
		{
			$ok = true;
			foreach( $ignoreList as $ignore )
			{
				if ( strpos($jsFile, $ignore) > -1 )
				{
					$ok = false;
				}
			}
			
			if ( $ok == false )
				continue;
				
			$data  = file_get_contents( $jsFile );
			//$bigJs .= "\n\n//***********************************************************************";
			//$bigJs .= "\n\n//**************************".$jsFile."**************************";
			//$bigJs .= "\n\n//***********************************************************************";
			$bigJs .= "\n\n".$data."\n\n";
		}
		
		
		//$bigJs = str_replace(array("\n","\r","\t"), "", $bigJs);
		return $bigJs;
	}	
	
	function writeExternals( $p_srcDir )
	{
		$data = "";
		$jsFiles = scanRecursively( $p_srcDir ); 
		$bigJs = "";
		$className = "";
		
		foreach( $jsFiles as $jsFile )
		{
			$index = strrpos( $jsFile, "/" );
			$className = substr( $jsFile, $index + 1 );
			$className = str_replace( ".js", "", $className );
			$bigJs .= "\n window['".$className."'] = ".$className.";";
		}
		
		return $bigJs;
	}

	function scanRecursively( $p_dir )
	{
			
		$list = scandir( $p_dir );
		$fileList = array();
		$isFile = false;
		
		foreach( $list as $file )
		{
			
			if ( $file == ".." || $file == '.' )
				continue;
				
			$isFile = is_file( $p_dir.$file );
			
			if ( $isFile )
			{
				$fileList[] = $p_dir.$file;
			}
			else
			{
				$fileList = array_merge( $fileList, scanRecursively( $p_dir.$file."/" ) );
			}
			
		}
		
		return $fileList;
	}
	
	
	
	// generate
	$data = "";
	$externs = "";
	$currentDir = realPath( dirname(__FILE__) );
	
	
	// utils
	
	/**********************************************/
	$jsDir = $currentDir.'/../src/apps/';
	$outputDir = $currentDir.'/../src/';
	
	$cleanFiles = array(
		"editorModel.full.js", "editorFiche.full.js", "printer.full.js",
		"editorModel.js", "editorFiche.js", "printer.js",
	);
	
	foreach( $cleanFiles as $value )
	{
		if ( file_exists($outputDir.$value))
		{
			unlink($outputDir.$value);
		}
	}
	
	
	
	/********************************************** write*/
	file_put_contents($outputDir."editorModel.full.js", packJs( $jsDir, array('EditorFiche','Printer') ));
	
	/********************************************** write*/
	file_put_contents($outputDir."editorFiche.full.js", packJs( $jsDir, array('EditorModel','Printer') ));
	
	/********************************************** write*/
	file_put_contents($outputDir."printer.full.js", packJs( $jsDir, array('EditorModel','EditorFiche') ));
	
	
	
	
?>